package com.example.projectmanagement.controller.study;

import com.example.projectmanagement.dto.study.ModuleDto;
import com.example.projectmanagement.dto.study.LessonDto;
import com.example.projectmanagement.dto.study.CourseDto;
import com.example.projectmanagement.model.study.Course;
import com.example.projectmanagement.model.study.Module;
import com.example.projectmanagement.model.study.Lesson;
import com.example.projectmanagement.model.study.Category;
import com.example.projectmanagement.model.User;
import com.example.projectmanagement.repository.study.CategoryRepository;
import com.example.projectmanagement.repository.study.LessonRepository;
import com.example.projectmanagement.service.study.ContentService;
import com.example.projectmanagement.service.UserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/study/courses")
@CrossOrigin
public class CourseController {

    @Autowired
    private ContentService contentService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private CategoryRepository categoryRepository;
    
    @Autowired
    private LessonRepository lessonRepository;

    /**
     * 创建课程（支持封面图片上传）
     */
    @PostMapping
    @PreAuthorize("hasRole('LECTURER') or hasRole('ADMIN')")
    public ResponseEntity<Course> createCourse(
            @RequestBody Course course,
            @RequestParam(value = "coverImage", required = false) MultipartFile coverImage) {
        try {
            Long currentUserId = getCurrentUserId();
            if (currentUserId == null) {
                return ResponseEntity.status(401).build();
            }
            
            Optional<User> userOpt = userService.getUserById(currentUserId);
            if (!userOpt.isPresent()) {
                return ResponseEntity.status(401).build();
            }
            
            // 如果有封面图片，先上传图片
            if (coverImage != null && !coverImage.isEmpty()) {
                // 调用文件上传API上传封面图片
                // 这里简单处理，实际应用中应该调用上传服务
                String fileName = UUID.randomUUID().toString() + "_" + coverImage.getOriginalFilename();
                // 在实际实现中，应保存文件并设置封面图片路径
                course.setCoverImage(fileName);
            }
            
            Course createdCourse = contentService.createCourse(course, userOpt.get());
            return ResponseEntity.ok(createdCourse);
        } catch (Exception e) {
            return ResponseEntity.status(500).build();
        }
    }

    /**
     * 更新课程
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasRole('LECTURER') or hasRole('ADMIN')")
    public ResponseEntity<Course> updateCourse(@PathVariable Long id, @RequestBody Course courseDetails) {
        try {
            Course updatedCourse = contentService.updateCourse(id, courseDetails);
            return ResponseEntity.ok(updatedCourse);
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }
    
    /**
     * 上传课程视频
     */
    @PostMapping("/{courseId}/videos")
    @PreAuthorize("hasRole('LECTURER') or hasRole('ADMIN')")
    public ResponseEntity<String> uploadCourseVideo(@PathVariable Long courseId, 
                                                   @RequestParam("video") MultipartFile videoFile) {
        // 实现视频上传逻辑
        return ResponseEntity.ok("视频上传成功");
    }
    
    /**
     * 获取课程的视频列表
     */
    @GetMapping("/{courseId}/videos")
    @PreAuthorize("hasRole('LECTURER') or hasRole('ADMIN') or hasRole('STUDENT')")
    public ResponseEntity<List<Lesson>> getCourseVideos(@PathVariable Long courseId) {
        // 实现获取课程视频列表逻辑
        return ResponseEntity.ok(java.util.Collections.emptyList());
    }
    
    /**
     * 设置课程分类
     */
    @PutMapping("/{courseId}/category")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<Course> setCourseCategory(@PathVariable Long courseId, 
                                                   @RequestBody Map<String, String> categoryData) {
        // 实现设置课程分类逻辑
        Course course = new Course();
        course.setId(courseId);
        return ResponseEntity.ok(course);
    }
    
    /**
     * 设置课程标签
     */
    @PutMapping("/{courseId}/tags")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<Course> setCourseTags(@PathVariable Long courseId, 
                                                @RequestBody List<String> tags) {
        // 实现设置课程标签逻辑
        Course course = new Course();
        course.setId(courseId);
        return ResponseEntity.ok(course);
    }
    
    /**
     * 获取课程分类列表
     */
    @GetMapping("/categories")
    public ResponseEntity<List<Category>> getCourseCategories() {
        // 从数据库查询课程分类
        List<Category> categories = categoryRepository.findAll();
        return ResponseEntity.ok(categories);
    }
    
    /**
     * 创建课程分类
     */
    @PostMapping("/categories")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<Category> createCategory(@RequestBody Category category) {
        // 保存分类到数据库
        Category savedCategory = categoryRepository.save(category);
        return ResponseEntity.ok(savedCategory);
    }

    /**
     * 获取课程分页列表
     */
    @GetMapping
    public ResponseEntity<Page<Course>> getCourses(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String subcategory,
            @RequestParam(required = false) String keyword) {
        
        Pageable pageable = PageRequest.of(page, size);
        
        Page<Course> courses;
        if (status != null && !status.isEmpty()) {
            courses = contentService.getCoursesByStatus(status, pageable);
        } else if (category != null && !category.isEmpty()) {
            if (subcategory != null && !subcategory.isEmpty()) {
                courses = contentService.getCoursesByCategoryAndSubcategory(category, subcategory, pageable);
            } else {
                courses = contentService.getCoursesByCategory(category, pageable);
            }
        } else if (keyword != null && !keyword.isEmpty()) {
            courses = contentService.searchCourses(keyword, pageable);
        } else {
            courses = contentService.getCourses(pageable);
        }
        
        return ResponseEntity.ok(courses);
    }
    
    /**
     * 发布课程
     */
    @PutMapping("/{id}/publish")
    @PreAuthorize("hasRole('LECTURER') or hasRole('ADMIN')")
    public ResponseEntity<Course> publishCourse(@PathVariable Long id) {
        try {
            Course course = contentService.publishCourse(id);
            return ResponseEntity.ok(course);
        } catch (Exception e) {
            return ResponseEntity.status(400).build();
        }
    }
    
    /**
     * 取消发布课程
     */
    @PutMapping("/{id}/unpublish")
    @PreAuthorize("hasRole('LECTURER') or hasRole('ADMIN')")
    public ResponseEntity<Course> unpublishCourse(@PathVariable Long id) {
        try {
            Course course = contentService.unpublishCourse(id);
            return ResponseEntity.ok(course);
        } catch (Exception e) {
            return ResponseEntity.status(400).build();
        }
    }
    
    /**
     * 删除课程
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('LECTURER') or hasRole('ADMIN')")
    public ResponseEntity<Void> deleteCourse(@PathVariable Long id) {
        try {
            contentService.deleteCourse(id);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.status(400).build();
        }
    }
    
    
    /**
     * 获取已发布的课程（供学习者浏览）
     */
    @GetMapping("/published")
    public ResponseEntity<Page<Course>> getPublishedCourses(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String subcategory,
            @RequestParam(required = false) String keyword) {
        
        Pageable pageable = PageRequest.of(page, size);
        Page<Course> courses = contentService.getPublishedCourses(category, subcategory, keyword, pageable);
        return ResponseEntity.ok(courses);
    }

    /**
     * 根据ID获取课程
     */
    @GetMapping("/{id}")
    public ResponseEntity<CourseDto> getCourseById(@PathVariable Long id) {
        Optional<Course> courseOpt = contentService.getCourseById(id);
        if (courseOpt.isPresent()) {
            Course course = courseOpt.get();
            CourseDto courseDto = contentService.convertToDto(course);
            return ResponseEntity.ok(courseDto);
        } else {
            return ResponseEntity.notFound().build();
        }
    }
    
    /**
     * 根据分类获取所有子分类
     */
    @GetMapping("/subcategories")
    public ResponseEntity<List<String>> getSubcategoriesByCategory(@RequestParam String category) {
        List<String> subcategories = contentService.getSubcategoriesByCategory(category);
        return ResponseEntity.ok(subcategories);
    }

    /**
     * 创建模块
     */
    @PostMapping("/{courseId}/modules")
    public ResponseEntity<Module> createModule(@PathVariable Long courseId, @RequestBody Module module) {
        module.setCourse(new com.example.projectmanagement.model.study.Course());
        module.getCourse().setId(courseId);
        Module createdModule = contentService.createModule(module);
        return ResponseEntity.ok(createdModule);
    }

    /**
     * 更新模块
     */
    @PutMapping("/modules/{id}")
    public ResponseEntity<Module> updateModule(@PathVariable Long id, @RequestBody Module moduleDetails) {
        try {
            Module updatedModule = contentService.updateModule(id, moduleDetails);
            return ResponseEntity.ok(updatedModule);
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 根据课程获取模块列表
     */
    @GetMapping("/{courseId}/modules")
    public ResponseEntity<List<ModuleDto>> getModulesByCourse(@PathVariable Long courseId) {
        List<Module> modules = contentService.getModulesByCourse(courseId);
        List<ModuleDto> moduleDtos = modules.stream().map(this::convertToModuleDto).collect(Collectors.toList());
        return ResponseEntity.ok(moduleDtos);
    }

    /**
     * 根据ID获取模块
     */
    @GetMapping("/modules/{id}")
    public ResponseEntity<Module> getModuleById(@PathVariable Long id) {
        Optional<Module> module = contentService.getModuleById(id);
        return module.map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    /**
     * 删除模块
     */
    @DeleteMapping("/modules/{id}")
    public ResponseEntity<Void> deleteModule(@PathVariable Long id) {
        try {
            contentService.deleteModule(id);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 创建课时
     */
    @PostMapping("/modules/{moduleId}/lessons")
    public ResponseEntity<Lesson> createLesson(@PathVariable Long moduleId, @RequestBody Lesson lesson) {
        lesson.setModule(new com.example.projectmanagement.model.study.Module());
        lesson.getModule().setId(moduleId);
        Lesson createdLesson = contentService.createLesson(lesson);
        return ResponseEntity.ok(createdLesson);
    }

    /**
     * 更新课时
     */
    @PutMapping("/lessons/{id}")
    public ResponseEntity<Lesson> updateLesson(@PathVariable Long id, @RequestBody Lesson lessonDetails) {
        try {
            Lesson updatedLesson = contentService.updateLesson(id, lessonDetails);
            return ResponseEntity.ok(updatedLesson);
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 根据模块获取课时列表
     */
    @GetMapping("/modules/{moduleId}/lessons")
    public ResponseEntity<List<LessonDto>> getLessonsByModule(@PathVariable Long moduleId) {
        List<Lesson> lessons = contentService.getLessonsByModule(moduleId);
        List<LessonDto> lessonDtos = lessons.stream().map(this::convertToLessonDto).collect(Collectors.toList());
        return ResponseEntity.ok(lessonDtos);
    }

    /**
     * 根据ID获取课时
     */
    @GetMapping("/lessons/{id}")
    public ResponseEntity<Lesson> getLessonById(@PathVariable Long id) {
        Optional<Lesson> lesson = contentService.getLessonById(id);
        return lesson.map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    /**
     * 删除课时
     */
    @DeleteMapping("/lessons/{id}")
    public ResponseEntity<Void> deleteLesson(@PathVariable Long id) {
        try {
            contentService.deleteLesson(id);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 获取当前认证用户的ID
     */
    private Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            String username = userDetails.getUsername();
            return userService.getUserByUsername(username).map(User::getId).orElse(null);
        }
        return null;
    }

    /**
     * 转换Module到ModuleDto
     */
    private ModuleDto convertToModuleDto(Module module) {
        ModuleDto dto = new ModuleDto();
        dto.setId(module.getId());
        dto.setTitle(module.getTitle());
        dto.setDescription(module.getDescription());
        dto.setDisplayOrder(module.getDisplayOrder());
        if (module.getCourse() != null) {
            dto.setCourseId(module.getCourse().getId());
        }
        dto.setCreateTime(module.getCreateTime());
        dto.setUpdateTime(module.getUpdateTime());
        return dto;
    }

    /**
     * 转换Lesson到LessonDto
     */
    private LessonDto convertToLessonDto(Lesson lesson) {
        LessonDto dto = new LessonDto();
        dto.setId(lesson.getId());
        dto.setTitle(lesson.getTitle());
        dto.setContent(lesson.getContent());
        dto.setLessonType(lesson.getLessonType());
        dto.setVideoUrl(lesson.getVideoUrl());
        dto.setDocumentUrl(lesson.getDocumentUrl());
        dto.setEstimatedDuration(lesson.getEstimatedDuration());
        dto.setDisplayOrder(lesson.getDisplayOrder());
        if (lesson.getModule() != null) {
            dto.setModuleId(lesson.getModule().getId());
        }
        dto.setCreateTime(lesson.getCreateTime());
        dto.setUpdateTime(lesson.getUpdateTime());
        return dto;
    }
}